package com.intelligent.service;

import com.intelligent.dto.NoticeDTO;
import com.intelligent.entity.Notice;
import com.intelligent.websocket.NoticeWebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息推送服务
 */
@Service
public class NotificationPushService {

    private static final Logger logger = LoggerFactory.getLogger(NotificationPushService.class);

    /**
     * 推送通知给指定用户
     *
     * @param userId 用户ID
     * @param notice 通知信息
     */
    public void pushNoticeToUser(String userId, Notice notice) {
        try {
            NoticeDTO noticeDTO = convertToDTO(notice);
            Map<String, Object> message = new HashMap<>();
            message.put("type", "notice");
            message.put("data", noticeDTO);
            message.put("timestamp", System.currentTimeMillis());
            
            NoticeWebSocketServer.sendNotice(userId, message);
            logger.info("成功推送通知给用户: {}, 通知ID: {}", userId, notice.getNoticeId());
        } catch (Exception e) {
            logger.error("推送通知失败, 用户ID: {}, 通知ID: {}", userId, notice.getNoticeId(), e);
        }
    }

    /**
     * 推送通知给多个用户
     *
     * @param userIds 用户ID列表
     * @param notice  通知信息
     */
    public void pushNoticeToUsers(List<String> userIds, Notice notice) {
        if (userIds == null || userIds.isEmpty()) {
            return;
        }
        
        for (String userId : userIds) {
            pushNoticeToUser(userId, notice);
        }
    }

    /**
     * 推送系统消息给所有在线用户
     *
     * @param notice 通知信息
     */
    public void pushNoticeToAll(Notice notice) {
        try {
            NoticeDTO noticeDTO = convertToDTO(notice);
            Map<String, Object> message = new HashMap<>();
            message.put("type", "system_notice");
            message.put("data", noticeDTO);
            message.put("timestamp", System.currentTimeMillis());
            
            NoticeWebSocketServer.sendToAll(message.toString());
            logger.info("成功推送系统通知给所有用户, 通知ID: {}", notice.getNoticeId());
        } catch (Exception e) {
            logger.error("推送系统通知失败, 通知ID: {}", notice.getNoticeId(), e);
        }
    }

    /**
     * 推送未读消息数量更新
     *
     * @param userId      用户ID
     * @param unreadCount 未读数量
     */
    public void pushUnreadCountUpdate(String userId, Integer unreadCount) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("type", "unread_count");
            message.put("data", unreadCount);
            message.put("timestamp", System.currentTimeMillis());
            
            NoticeWebSocketServer.sendNotice(userId, message);
            logger.info("成功推送未读数量更新给用户: {}, 未读数量: {}", userId, unreadCount);
        } catch (Exception e) {
            logger.error("推送未读数量更新失败, 用户ID: {}", userId, e);
        }
    }

    /**
     * 推送通知状态更新（如已读状态）
     *
     * @param userId   用户ID
     * @param noticeId 通知ID
     * @param status   状态信息
     */
    public void pushNoticeStatusUpdate(String userId, Integer noticeId, String status) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("type", "notice_status_update");
            Map<String, Object> data = new HashMap<>();
            data.put("noticeId", noticeId);
            data.put("status", status);
            message.put("data", data);
            message.put("timestamp", System.currentTimeMillis());
            
            NoticeWebSocketServer.sendNotice(userId, message);
            logger.info("成功推送通知状态更新给用户: {}, 通知ID: {}, 状态: {}", userId, noticeId, status);
        } catch (Exception e) {
            logger.error("推送通知状态更新失败, 用户ID: {}, 通知ID: {}", userId, noticeId, e);
        }
    }

    /**
     * 获取当前在线用户数量
     *
     * @return 在线用户数量
     */
    public int getOnlineUserCount() {
        return NoticeWebSocketServer.getOnlineCount();
    }

    /**
     * 检查用户是否在线
     *
     * @param userId 用户ID
     * @return 是否在线
     */
    public boolean isUserOnline(String userId) {
        return NoticeWebSocketServer.getWebSocketMap().containsKey(userId);
    }

    /**
     * 转换为DTO
     */
    private NoticeDTO convertToDTO(Notice notice) {
        NoticeDTO dto = new NoticeDTO();
        BeanUtils.copyProperties(notice, dto);
        return dto;
    }
}